package com.example.testcoroutine

import android.content.Context
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemsIndexed
import com.google.accompanist.glide.rememberGlidePainter

class ComposeLoadActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val vm = MainViewModel()
            MaterialTheme {
                ProjectList(vm)
            }
        }

    }

    @Composable
    fun ProjectList(vm: MainViewModel) {
        val projects = vm.projects.collectAsLazyPagingItems()
        when (projects.loadState.refresh) {
            is LoadState.NotLoading -> LazyColumn(modifier = Modifier.background(
                color = Color(
                    0xfff5f5f5
                )
            ),
                content = {
                    itemsIndexed(projects) { _, project ->
                        ProjectItem(project = project!!)
                    }
                    when (projects.loadState.append) {
                        is LoadState.NotLoading -> itemsIndexed(projects) { _, project ->
                            ProjectItem(project = project!!)
                        }
                        is LoadState.Error -> item {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(8.dp),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center,
                            ) {
                                Button(onClick = {
                                    projects.retry()
                                }) {
                                    Text(text = "重试")
                                }
                            }

                        }
                        LoadState.Loading -> item {
                            LoadingPage()
                        }

                    }
                })

            is LoadState.Error -> ErrorPage { projects.refresh() }

            is LoadState.Loading -> LoadingPage()
        }

    }
}

@Composable
fun ProjectItem(project: Project) {
    Card(modifier = Modifier.padding(8.dp)) {
        Column(
            modifier = Modifier.padding(8.dp)
        ) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(text = project.title, style = MaterialTheme.typography.h6)
                    Text(
                        text = project.desc,
                        style = MaterialTheme.typography.body1,
                        color = Color.Gray,
                        modifier = Modifier.padding(top = 6.dp)
                    )
                }
                Image(
//            painter = rememberCoilPainter(puppy.puppyImageUrl),
                    painter = rememberGlidePainter(
                        request = project.envelopePic,
                        fadeIn = true
                    ),
                    contentDescription = null,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .width(57.dp)
                        .height(101.dp)
                        .padding(start = 4.dp)
                        .clip(RoundedCornerShape(corner = CornerSize(5.dp)))
                )
            }

            Row(modifier = Modifier.padding(top = 8.dp)) {
                Text(
                    text = project.author,
                    style = MaterialTheme.typography.body1,
                    color = Color.Gray
                )
                Text(
                    text = project.niceDate,
                    style = MaterialTheme.typography.body1,
                    color = Color.Gray,
                    modifier = Modifier.padding(start = 10.dp)
                )
            }

        }

    }
}

@Composable
fun LoadingPage(context: Context = LocalContext.current) {
    val animate by rememberInfiniteTransition().animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            tween(500, easing = LinearEasing),
            RepeatMode.Restart
        )
    )
    val radius = context.dp2px(80f)
    Canvas(modifier = Modifier.fillMaxSize()) {
        translate(size.width / 2 - radius, size.height / 2 - radius) {
            drawArc(
                Color.Green,
                0f,
                animate,
                false,
                size = Size(radius * 2f, radius * 2f),
                style = Stroke(context.dp2px(4f)),
                alpha = 0.6f
            )
        }
    }
}

fun Context.dp2px(dp: Float): Float {
    val density = resources.displayMetrics.density
    return dp * density + 0.5f
}

@Composable
fun ErrorPage(onclick: () -> Unit = {}) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            modifier = Modifier.size(300.dp, 180.dp),
            painter = painterResource(id = R.drawable.ic_launcher_foreground),
            contentDescription = "网络问题",
            contentScale = ContentScale.Crop
        )
        Button(modifier = Modifier.padding(8.dp), onClick = onclick) {
            Text(text = "网络不佳，请点击重试")
        }
    }
}
